// (C) 2011 L0H
// extract GIF global color map and output it to PPM format.
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include "gif_lib.h"
using namespace std;

void saveColorMap(const string& filename, ColorMapObject* cmo) {
	const int W = 20; // width[px]/color
	const int H = 20; // height[px]/color
	const int C = 16; // color/columns
	const int PICW = W*C;
	const int PICH = ceil(cmo->ColorCount/C) * H;
	vector<char> buf(PICW*PICH*3, 0xFF);
	int row = 0;
	for (int i = 0; i < cmo->ColorCount; ++i) {
		if (i != 0 && i % 16 == 0)
			++row;
		int base = PICW*(row*H)*3 + W*(i%16)*3;
		for (int j = 0; j < H; ++j) {
			for (int k = 0; k < W; ++k) {
				int p = base + PICW*j*3 + k*3;
				buf[p+0] = cmo->Colors[i].Red;
				buf[p+1] = cmo->Colors[i].Green;
				buf[p+2] = cmo->Colors[i].Blue;
			}
		}
	}
	ofstream ofs((filename+"-cm.ppm").c_str(), std::ios::binary);
	ofs << "P6" << endl
		<< PICW << " " << PICH << endl
		<< 255 << endl;
	ofs.write(&buf[0], buf.size());
}

int main(int argc, char** argv) {
	if (argc != 2) {
		cerr << "argc != 2" << endl;
		exit(1);
	}
	GifFileType* gf = DGifOpenFileName(argv[1]);
	if (!gf) {
		PrintGifError();
		exit(1);
	}
	if (DGifSlurp(gf) == GIF_ERROR) {
		PrintGifError();
		exit(1);
	}
	if (gf->SColorMap) {
		ColorMapObject* cmo = gf->SColorMap;
		cout << cmo->ColorCount << "colors" << endl;
		cout << cmo->BitsPerPixel << "bpp" <<endl;
		string filename = argv[1];
		saveColorMap(filename.substr(0, filename.length()-4), cmo);
	}
	DGifCloseFile(gf);
	return 0;
}

